<script lang="ts" setup>
import { findStore } from '@/api/store'
import { getToken } from '@/utils/cache/cookies'
import { useRoute, useRouter } from 'vue-router'
import { findStoreResponseData, StoreTableCol } from '@/api/store/types/store'
import { ref, onMounted, defineAsyncComponent, reactive, onActivated } from 'vue'
import { useActivated } from '@/hooks/useActivated'
import StoreInfoPopover from '@/components/popover/StoreInfo.vue'
import dayjs from 'dayjs'
import { useMap } from '@/hooks/useMap'
import StoreImg from '@/assets/map/operatorsInfo/store.png'
import RedStoreImg from '@/assets/map/operatorsInfo/redstore.png'
import LocationImg from '@/assets/map/operatorsInfo/location.png'
const route = useRoute()
const router = useRouter()
const TimeRentBikeTabPane = defineAsyncComponent(
  () => import('@/views/personnel/operators/tabpane/TimeRentBikeTabPane.vue')
)
const LongRentBikeTabPane = defineAsyncComponent(
  () => import('@/views/personnel/operators/tabpane/LongRentBikeTabPane.vue')
)
const BikeRentTermTabPane = defineAsyncComponent(
  () => import('@/views/personnel/operators/tabpane/BikeRentTermTabPane.vue')
)
const CabinetTabPane = defineAsyncComponent(
  () => import('@/views/personnel/operators/tabpane/CabinetTabPane.vue')
)
const BatterySwapPackageTabPane = defineAsyncComponent(
  () => import('@/views/personnel/operators/tabpane/BatterySwapPackageTabPane.vue')
)
const RentOrderTabPane = defineAsyncComponent(
  () => import('@/views/personnel/operators/tabpane/RentOrderTabPane.vue')
)
const ActivityTabPane = defineAsyncComponent(
  () => import('@/views/personnel/operators/tabpane/ActivityTabPane.vue')
)
defineOptions({
  name: 'OperatorsInfo'
})
/**
 * 获取加盟商旗下所有门店
 * @param allStoreData - 旗下所有门店数据
 * @param lastdata - 当前门店数据
 * @param storeInfo - 当前门店除车辆数量的信息
 * @param boxCount - 换电柜数量
 * @param rentOrderCount - 租赁订单数量
 * @param bikeLongTermCount - 长租车数量
 * @param bikeLongTermProductsCount - 车辆租赁套餐数量
 * @param shortBikeCount - 短租车数量
 * @param longtitude - 门店经度
 * @param latitude - 门店纬度
 */
const allStoreData = ref<findStoreResponseData[]>([])
const lastdata = ref<findStoreResponseData>()
const storeInfo = ref<StoreTableCol>()
const boxCount = ref<number>(0)
const rentOrderCount = ref<number>(0)
const activityCount = ref<number>(0)
const bikeLongTermCount = ref<number>(0)
const shortBikeCount = ref<number>(0)
const bikeLongTermProductsCount = ref<number>(0)
const longtitude = ref<number>(0)
const latitude = ref<number>(0)
const getOtherStoreData = async () => {
  try {
    const res = await findStore({
      token: getToken() ?? '',
      merchantId: route.query.merchantId as string
    })
    if (res.statusCode === '0') {
      allStoreData.value = res.data
      lastdata.value = allStoreData.value.find(
        (store) => store.storeInfo.storeId == route.query.storeId
      )
      storeInfo.value = lastdata.value?.storeInfo
      boxCount.value = lastdata.value?.boxCount ?? 0
      rentOrderCount.value = lastdata.value?.rentOrderCount ?? 0
      activityCount.value = lastdata.value?.activityCount ?? 0
      bikeLongTermCount.value = lastdata.value?.bikeLongTermCount ?? 0
      shortBikeCount.value = lastdata.value?.shortBikeCount ?? 0
      bikeLongTermProductsCount.value = lastdata.value?.bikeLongTermProductsCount ?? 0
      longtitude.value = Number(storeInfo.value?.longtitude ?? 0)
      latitude.value = Number(storeInfo.value?.latitude ?? 0)
    }
  } catch (error) {
    console.error(error)
  }
}
/**
 * 处理点击其他门店逻辑
 */
const handleCardClick = (data: StoreTableCol) => {
  lastdata.value = allStoreData.value.find((store) => store.storeInfo.storeId == data.storeId)
  storeInfo.value = lastdata.value?.storeInfo
  boxCount.value = lastdata.value?.boxCount ?? 0
  rentOrderCount.value = lastdata.value?.rentOrderCount ?? 0
  bikeLongTermCount.value = lastdata.value?.bikeLongTermCount ?? 0
  activityCount.value = lastdata.value?.activityCount ?? 0
  shortBikeCount.value = lastdata.value?.shortBikeCount ?? 0
  bikeLongTermProductsCount.value = lastdata.value?.bikeLongTermProductsCount ?? 0
  longtitude.value = Number(storeInfo.value?.longtitude ?? 0)
  latitude.value = Number(storeInfo.value?.latitude ?? 0)
  router.replace({
    name: 'OperatorsInfo',
    query: {
      merchantId: watchParams.merchantId,
      storeId: storeInfo.value?.storeId
    }
  })
  handleCoverInit()
  handleTabChange()
}
/**
 * 处理地图
 */
const isInit = ref<boolean>(false)
const mapContainer = ref<HTMLDivElement>()
const marker = ref<AMap.Marker>()
const infowindow = ref<AMap.InfoWindow>()
const { map, initAmap, geocoder } = useMap(mapContainer, [longtitude.value, latitude.value])

const handleMarkerClick = (e: any) => {
  if (infowindow.value?.getIsOpen()) {
    infowindow.value.close()
    marker.value?.setIcon(
      new AMap.Icon({
        image: StoreImg,
        imageSize: new AMap.Size(59, 63),
        size: new AMap.Size(59, 63)
      })
    )
  } else {
    marker.value?.setIcon(
      new AMap.Icon({
        image: RedStoreImg,
        imageSize: new AMap.Size(59, 63),
        size: new AMap.Size(59, 63)
      })
    )
    infowindow.value?.open(map.value!, e.lnglat)
  }
}

const handleCoverInit = () => {
  const center = new AMap.LngLat(longtitude.value, latitude.value)

  marker.value = new AMap.Marker({
    position: center,
    map: map.value!,
    icon: new AMap.Icon({
      image: StoreImg,
      imageSize: new AMap.Size(59, 63),
      size: new AMap.Size(59, 63)
    }),
    offset: new AMap.Pixel(-30, -63)
  })
  infowindow.value = new AMap.InfoWindow({
    isCustom: true,
    position: center,
    autoMove: true,
    offset: new AMap.Pixel(0, -60)
  })
  infowindow.value?.open(map.value!, center)
  marker.value.on('click', handleMarkerClick)
  geocoder.value.getAddress(center, (status: any, result: any) => {
    const poilocation = result.regeocode.formattedAddress
    infowindow.value?.setContent(
      `<div class="map-infowindow_location">
                <span class="map-infowindow_storeName">${storeInfo.value?.storeName}</span>
                <div class="details-location">
                  <img src="${LocationImg}"/>
                  <span>${poilocation}</span>
                </div>
              </div>`
    )
  })
  map.value?.setCenter(center)
}
const activeName = ref<string>('timerent')
/** 各tabpane ref */
const timeRentBikeTabPaneRef = ref<InstanceType<typeof TimeRentBikeTabPane> | null>(null)
const longRentBikeTabPaneRef = ref<InstanceType<typeof LongRentBikeTabPane> | null>(null)
const bikeRentTermTabPaneRef = ref<InstanceType<typeof BikeRentTermTabPane> | null>(null)
const cabinetTabPaneRef = ref<InstanceType<typeof CabinetTabPane> | null>(null)
const batterySwapPackageTabPaneRef = ref<InstanceType<typeof BatterySwapPackageTabPane> | null>(
  null
)
const rentOrderTabPaneRef = ref<InstanceType<typeof RentOrderTabPane> | null>(null)
const activityTabPaneRef = ref<InstanceType<typeof ActivityTabPane> | null>(null)
/** 切换选项卡 */
const handleTabChange = () => {
  switch (activeName.value) {
    case 'timerent':
      timeRentBikeTabPaneRef.value?.setId(storeInfo.value?.storeId as string)
      timeRentBikeTabPaneRef.value?.load()
      break
    case 'longrent':
      longRentBikeTabPaneRef.value?.setId(storeInfo.value?.storeId as string)
      longRentBikeTabPaneRef.value?.load()
      break
    case 'biketerm':
      bikeRentTermTabPaneRef.value?.setId(storeInfo.value?.storeId as string)
      bikeRentTermTabPaneRef.value?.getData()
      break
    case 'cabinet':
      cabinetTabPaneRef.value?.setId(storeInfo.value?.storeId as string)
      cabinetTabPaneRef.value?.load()
      break
    case 'batteryswappackage':
      batterySwapPackageTabPaneRef.value?.setId(storeInfo.value?.storeId as string)
      batterySwapPackageTabPaneRef.value?.load()
      break
    case 'rentorder':
      rentOrderTabPaneRef.value?.setTabId(storeInfo.value?.storeId as string)
      rentOrderTabPaneRef.value?.handleTabChange()
      break
    case 'activity':
      activityTabPaneRef.value?.setId(storeInfo.value?.storeId as string)
      activityTabPaneRef.value?.load()
      break
    default:
      break
  }
}
onMounted(async () => {
  isInit.value = await initAmap()
  activedInit()
})
const activedInit = async () => {
  await getOtherStoreData()
  handleCoverInit()
  handleTabChange()
}
onActivated(() => {
  watchParams.merchantId = route.query.merchantId
  watchParams.storeId = route.query.storeId
})
const watchParams = reactive({
  merchantId: route.query.merchantId,
  storeId: route.query.storeId
})
useActivated(
  watchParams,
  { watchParams },
  [
    { key: 'merchantId', path: 'watchParams.merchantId' },
    { key: 'storeId', path: 'watchParams.storeId' }
  ],
  activedInit,
  []
)
</script>

<template>
  <div class="xy-container--split">
    <div class="xy-container__header operators-info-top">
      <div class="store-info_title">
        <div>
          <span>{{ storeInfo ? storeInfo.storeName : '' }}</span>
          <el-popover
            placement="bottom-start"
            trigger="hover"
            popper-class="operators-info-popover"
            width="auto"
          >
            <store-info-popover
              v-for="item in allStoreData"
              :key="item.storeInfo.storeId"
              :data="item.storeInfo"
              :isDivider="false"
              @card-click="handleCardClick"
            />
            <template #reference>
              <el-button plain>切换门店</el-button>
            </template>
          </el-popover>
        </div>
        <div>
          <div>
            加盟地区:&nbsp;&nbsp;<span>{{ storeInfo ? storeInfo.cityName : '' }}</span>
          </div>
          <div>
            加入时间:&nbsp;&nbsp;<span>{{
              dayjs(storeInfo ? storeInfo.createdTime : '').format('YYYY-MM-DD HH:mm:ss')
            }}</span>
          </div>
          <div>
            营业时间:&nbsp;&nbsp;<span>{{ storeInfo ? storeInfo.serviceTime : '' }}</span>
          </div>
          <template v-if="storeInfo">
            <el-tag type="warning" plain v-if="storeInfo.status == '0'">已打烊</el-tag>
            <el-tag type="success" plain v-if="storeInfo.status == '1'">营业中</el-tag>
          </template>
        </div>
      </div>
      <div ref="mapContainer" id="map-container" h-320 mt-15 />
    </div>
    <div class="xy-container__content operators-info-bottom">
      <el-tabs
        v-model="activeName"
        class="operators-info-card red-tab-active"
        @tab-change="handleTabChange"
      >
        <el-tab-pane name="timerent">
          <template #label>
            <div class="el-tab-title">
              <span>短租车辆</span>
              <span>{{ shortBikeCount }}辆</span>
            </div>
          </template>
          <time-rent-bike-tab-pane ref="timeRentBikeTabPaneRef" />
        </el-tab-pane>
        <el-tab-pane name="longrent">
          <template #label>
            <div class="el-tab-title">
              <span>长租车辆</span>
              <span>{{ bikeLongTermCount }}辆</span>
            </div>
          </template>
          <long-rent-bike-tab-pane ref="longRentBikeTabPaneRef" />
        </el-tab-pane>
        <el-tab-pane name="biketerm">
          <template #label>
            <div class="el-tab-title">
              <span>长租套餐</span>
              <span>{{ bikeLongTermProductsCount }}个</span>
            </div>
          </template>
          <bike-rent-term-tab-pane ref="bikeRentTermTabPaneRef" />
        </el-tab-pane>
        <el-tab-pane name="batteryswappackage">
          <template #label>
            <div class="el-tab-title">
              <span>换电套餐</span>
              <span>{{ activityCount }}个</span>
            </div>
          </template>
          <battery-swap-package-tab-pane ref="batterySwapPackageTabPaneRef" />
        </el-tab-pane>
        <el-tab-pane name="cabinet">
          <template #label>
            <div class="el-tab-title">
              <span>换电柜</span>
              <span>{{ boxCount }}个</span>
            </div>
          </template>
          <cabinet-tab-pane ref="cabinetTabPaneRef" />
        </el-tab-pane>
        <el-tab-pane name="rentorder">
          <template #label>
            <div class="el-tab-title">
              <span>订单</span>
              <span>{{ rentOrderCount >= 99 ? '99+' : rentOrderCount }}条</span>
            </div>
          </template>
          <rent-order-tab-pane ref="rentOrderTabPaneRef" />
        </el-tab-pane>
        <el-tab-pane name="activity">
          <template #label>
            <div class="el-tab-title">
              <span>门店活动</span>
              <span>{{ activityCount }}个</span>
            </div>
          </template>
          <activity-tab-pane ref="activityTabPaneRef" />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<style scoped lang="scss">
.operators-info-bottom,
.operators-info-top {
  width: 100%;
  background: #fff;
  box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.05);
  border-radius: 5px;
}
.operators-info-top {
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  .store-info_title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 10px;
    > div:first-child {
      display: flex;
      align-items: center;
      > span:first-child {
        font-size: 20px;
        font-family: PingFang SC;
        font-weight: 500;
        line-height: 28px;
        color: rgba(0, 0, 0, 0.87);
        margin-right: 10px;
      }
    }
    > div:last-child {
      display: flex;
      align-items: center;
      > div {
        color: #888888;
        font-size: 14px;
        font-family: PingFang SC;
        line-height: 20px;
        margin-left: 40px;
        > span {
          color: #333333;
          font-size: 14px;
          font-family: PingFang SC;
          line-height: 20px;
        }
      }
      .el-tag {
        margin-left: 10px;
      }
    }
  }
}
:deep(.operators-info-bottom) {
  margin-top: 20px;
  .operators-info-card {
    margin-top: 20px;
    margin-bottom: 20px;
    > .el-tabs__header {
      padding: 27px 20px 0px 15px;
      position: relative;
      margin: 0 0 15px;
      .el-tabs__item {
        padding: 0 20px;
        height: 50px;
        box-sizing: border-box;
        line-height: 22px;
        display: inline-block;
        list-style: none;
        font-size: 16px;
        font-weight: 500;
        color: #303133;
        position: relative;
        .el-tab-title {
          display: flex;
          flex-direction: column;
          align-items: center;
          padding: 0px 15px 0 15px;
          > span:last-child {
            font-size: 14px;
            line-height: 20px;
            color: #999999;
          }
        }
      }
      > .el-tabs__item.is-top:nth-child(2) {
        padding-left: 0;
      }
    }
    > .el-tabs__content {
      overflow: hidden;
      position: relative;
      padding: 0px 15px;
    }
  }
  .el-tabs__item.is-active {
    color: var(--el-color-primary) !important;
  }
}
</style>
